// ==UserScript==
// @name         物理实验助手
// @namespace    http://tampermonkey.net/
// @version      1.2
// @description  获取部分预习答案,获取实验报告成绩
// @author       Tiosa
// @match        *://192.168.70.28:*/*
// @run-at       document-start
// @grant        GM_xmlhttpRequest
// @grant        GM_setValue
// @grant        GM_getValue
// ==/UserScript==

/* ==UserConfig==
main:
    stuid:
        title: 学生id
        description: 如2024640000
        type: number
==/UserConfig== */
(function() {
    'use strict';

    // 拦截 XMLHttpRequest
    const originalXHROpen = XMLHttpRequest.prototype.open;
    const originalXHRSend = XMLHttpRequest.prototype.send;
    const get_ans = function(question){
        return question.querySelector("StdAnswer").textContent;
    };
    const get_ans_text = function(question,ans){
        const inlines = question.getElementsByTagName(ans+"Choice")[0].getElementsByTagName("Inline");
        var text = "";
        for (let i = 0; i < inlines.length; i++){
            if (inlines[i].getAttribute("Type") == "Run"){
                if (inlines[i].getAttribute("Text").length < 100){
                    text += inlines[i].getAttribute("Text");
                }
            }
        }
        return text;
    };
    const get_ss_ans = function(questions){
        var ret = "";
        for (let i = 0; i < questions.length; i++){
            ret+="第"+String(i+1)+"题: "+get_ans_text(questions[i], get_ans(questions[i]))+"\n";
        }
        return ret;
    };
    const get_ms_ans = function(questions){
        var ret = "";
        for (let i = 0; i < questions.length; i++){
            ans = get_ans(questions[i]);
            for (let j = 0; j < ans.length; j++){
                ret+="第"+String(i+1)+"题: "+get_ans_text(questions[i], ans[j])+"\n";
            }
        }
        return ret;
    };
    const get_bl_tf_ans = function(questions){
        var ret = "";
        for (let i = 0; i < questions.length; i++){
            ret+="第"+String(i+1)+"题: "+get_ans(questions[i])+"\n";
        }
        return ret;
    };
    XMLHttpRequest.prototype.open = function(method, url) {
        this._method = method;
        this._url = url;
        return originalXHROpen.apply(this, arguments);
    };

    XMLHttpRequest.prototype.send = function(data) {
        this.addEventListener('readystatechange', function() {
            if (this.readyState === 4) {
                console.log(
                    '[XHR] 拦截到请求:',
                    this._method,
                    this._url,
                    '\n响应数据:', this.responseText
                );
            // 提交实验报告响应
            if (this.responseText.startsWith("{\"Score\":")){
                let ret = JSON.parse(this.responseText);
                alert("你的实验报告成绩为"+ret.Score);
            }
            // 预习实验响应
            if (this.responseText.startsWith("{\"ExamID\":")){
                let ret = JSON.parse(this.responseText);
                let exid = ret.ExamID;
                let paper = ret.UsePapers;
                let stuid = GM_getValue("main.stuid");
                GM_xmlhttpRequest({
                    method:"POST",
                    url:"http://192.168.70.28:7102/ExamYuXIAPI/FindPaperContentByPaperID",
                    headers:{"Content-Type":"application/x-www-form-urlencoded; charset=utf-8"},
                    data:"ExamID="+exid+"&StudentID="+stuid+"&PaperID="+paper,
                    nocache:true,
                    onload:function(response) {
                        alert("检测到预习开始")
                        console.log("请求成功:", response.responseText);
                        const parser = new DOMParser();
                        const xmlDoc = parser.parseFromString(response.responseText, "text/xml");

                        // 检查是否解析成功
                        if (xmlDoc.getElementsByTagName("parsererror").length === 0) {
                            const questions = xmlDoc.getElementsByTagName("Question");
                            const ss = [];
                            const ms = [];
                            const bl = [];
                            const tf = [];
                            const other = [];
                            var ret = "";
                            for(let i = 0; i < questions.length; i++) {
                                switch(questions[i].getAttribute('Type')){
                                    case "SS":
                                        ss.push(questions[i]);
                                        break;
                                    case "MS":
                                        ms.push(questions[i]);
                                        break;
                                    case "BL":
                                        bl.push(questions[i]);
                                        break;
                                    case "TF":
                                        tf.push(questions[i]);
                                        break;
                                    default:
                                        other.push(questions[i]); 
                                }
                            }
                            ret = "单选答案:\n" + get_ss_ans(ss);
                            ret += "多选答案:\n" + get_ms_ans(ms);
                            ret += "选择填空题答案:\n" + get_bl_tf_ans(bl);
                            ret += "判断题答案:\n" + get_bl_tf_ans(tf);
                            alert(ret)
                            console.log("解析成功");
                        }
                    },
                    onerror:function(e) {
                        console.log("请求失败:", e);
                    }
                });
            }

            }
        });
        return originalXHRSend.apply(this, arguments);
    };
})();